package com.hexiang.error;

import com.hexiang.domain.BaseResult;
import org.apache.catalina.connector.ClientAbortException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理其他异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public Object exceptionHandler(HttpServletRequest req, HttpServletResponse resp, Exception e) throws IOException {
        logger.error("application occur error :", e);
        BaseResult result = new BaseResult(0, "HttpErrorController error:" + resp.getStatus());
        return doError(req, resp, result);
    }

    @ExceptionHandler(value = ClientAbortException.class)
    public Object clientAbortExceptionHandler(HttpServletRequest req, HttpServletResponse resp, ClientAbortException e) throws IOException {
        logger.warn("client abort :", e);
        return null;
    }

    private Object doError(HttpServletRequest req, HttpServletResponse resp, BaseResult result) throws IOException {
        resp.setContentType("application/json;charset=utf-8");
        resp.setStatus(500);
        PrintWriter out = resp.getWriter();
        out.write(result.toString());
        out.flush();
        out.close();
        return null;
    }

}